﻿using System;
using System.Threading;

using LeanEngine.Extensions;
using LeanEngine.Collections;
using LeanEngine.Business.Security.Entity;

namespace LeanEngine.Business.Security
{
    /// <summary>
    /// Represents a security context for access control implementation of methods based on profile.
    /// </summary>
    [SecureContext]
    public class SecureContext : ContextBoundObject
    {
        /// <summary>
        /// Initialize a new instance of LeanEngine.Business.Security.SecurityFacade class
        /// and sets the current principal.
        /// </summary>
        /// <exception cref="InvalidTokenException"></exception>
        /// <param name="securityToken">The token received after user login.</param>
        public SecureContext(Token securityToken)
        {
            if (securityToken.IsNull() ||
                securityToken.Name.IsNullOrEmpty() ||
                securityToken.Password.IsNullOrEmpty())
            {
                throw new InvalidTokenException();
            }

            var tmpSign = BusinessSecurity.GenerateTokenSign(securityToken.UserName, securityToken.Password, securityToken.TokenID);

            if (securityToken.AuthenticationSign != tmpSign)
            {
                throw new InvalidTokenException();
            }

            Thread.CurrentPrincipal = new SecurityPrincipal(securityToken);
        }
    }
}
